package com.teacher.hong.dao;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 基础数据访问层
 */
@Slf4j
@Repository
public class BaseDao {

    //数据库连接器
    Connection connection;

    @Resource
    public void setDataSource(DriverManagerDataSource dataSource) {
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 查询类
     *
     * @param sql
     * @return
     */
    public ResultSet query(String sql) throws SQLException {
        return query(sql, null);
    }

    /**
     * 查询类
     *
     * @param sql
     * @return
     */
    public ResultSet query(String sql, List<Object> params) throws SQLException {
        log.debug("SQL\t" + LocalDateTime.now() + "\t" + sql);
        if (params != null && params.size() > 0) log.debug("Params\t" + params);

        //准备好的报表/SQL
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (params != null) {
            int index = 1;
            for (Object param : params) {
                preparedStatement.setObject(index++, param);
            }
        }
        //执行准备好的报表/SQL
        ResultSet resultSet = preparedStatement.executeQuery();
        return resultSet;
    }


    /**
     * 增、删、改之类
     *
     * @param sql
     * @return
     */
    public int update(String sql) throws SQLException {
        return update(sql, null);
    }

    /**
     * 增、删、改之类
     *
     * @param sql
     * @param params 参数
     * @return
     */
    public int update(String sql, List<Object> params) throws SQLException {
        log.debug("SQL\t" + LocalDateTime.now() + "\t" + sql);
        if (params != null && params.size() > 0) log.debug("Params\t" + params);
        //准备好的报表/SQL
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (params != null) {
            int index = 1;
            for (Object param : params) {
                preparedStatement.setObject(index++, param);
            }
        }
        //执行准备好的报表/SQL
        return preparedStatement.executeUpdate();
    }


}
